import {
  ModalForm,
  ProFormGroup,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import ProLayout, {
  PageContainer,
  FooterToolbar,
} from '@ant-design/pro-layout';
import { history, useRequest } from 'umi';
import { InboxOutlined } from '@ant-design/icons';
import {
  message,
  Descriptions,
  Button,
  Breadcrumb,
  Table,
  Space,
  Upload,
  Modal,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { ProCard } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';
import { UploadOutlined, FileSearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import {
  getLabelAdapter,
  isPassAdapter,
  TitleAdapter,
} from '../../commons/Adapter';
import TbaleExplainMap from '@/components/TipsMap';

const { Dragger } = Upload;

export default () => {
  const formRef = useRef<ProFormInstance>();
  // const [proTableData, setProTableData] = useState([]);
  const [pageType, setPageType] = useState(
    history.location.pathname.replace(
      '/LabAchievements/ScientificResearch/OtherAchievements/EditOtherAchievements/',
      '',
    ),
  );
  const [descriptiondata, setDescriptionData] = useState<any>([]);
  const [modalDataSource, setModalDataSource] = useState([]); //modal的数据源
  const [selectKeys, setSelectKeys] = useState<any>(); //modal checkbox默认选中
  const [saveType, setSaveType] = useState(''); //modal 点击确认 调用新增、更新还是暂存接口
  const [isModalVisible, setIsModalVisible] = useState(false);

  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.docx,.doc,.pdf,.xls',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info?.file?.response?.code == 200) {
          formRef.current?.setFieldsValue({
            annexPath: info?.file?.response.data,
          });
          message.success(`${info.file.name} 上传成功！`);
        } else if (info?.file?.response?.code == 401) {
          message.error('用户登录过期请重新登陆！');
        } else {
          message.error(`${info.file.name} 上传失败`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  //获取其他成果详细信息
  const findYearAndOtherAchieveDetailById = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/yearAndOther/findYearAndOtherAchieveDetailById`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result, params) => {
        console.log(result);
      },
    },
  );
  //新增其他成果
  const addYearAndOtherAchieve = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/yearAndOther/addYearAndOtherAchieve`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/OtherAchievements');
        } else {
          message.error(result.msg);
        }
      },
      formatResult: (res) => res,
      manual: true,
    },
  );
  //暂存其他成果接口
  const addOrUpdateYearAndOtherAchieveTemp = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/yearAndOther/addOrUpdateYearAndOtherAchieveTemp`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/OtherAchievements');
        } else {
          message.error(result.msg);
        }
      },
      formatResult: (res) => res,
    },
  );

  //更新其他成果信息
  const updateYearAndOtherAchieve = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/yearAndOther/updateYearAndOtherAchieve`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/OtherAchievements');
        } else {
          message.error(result.msg);
        }
      },
      formatResult: (res) => res,
    },
  );
  //查找所有标签
  const getAllLabel = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getAllLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
    },
  );
  //添加标签
  const addLabelDetail = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/addLabelDetail',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        getAllLabel.run();
        message.success('添加成功');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //审核
  const updateStatusIpi = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //根据userList获取人员列表/user/getUserList
  const getUserList = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserList',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result) => {
        console.log(result);
        let resultTemp: any = [];
        result.map((item: any) => {
          resultTemp.push(item.webId);
        });
        console.log(resultTemp);
        setSelectKeys(resultTemp);
      },
    },
  );
  const showModal = (value: any) => {
    console.log(value);
    setModalDataSource(value);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    let paramTemp: any = [];
    selectKeys.map((element: any) => {
      paramTemp.push(
        getUserList?.data.filter((item: any) => item.webId === element)[0],
      );
    });
    let formRefData: any = formRef.current?.getFieldsValue();
    if (saveType === '暂存') {
      addOrUpdateYearAndOtherAchieveTemp.run({
        yearOrOther: '其他标志性成果',
        ...formRefData,
        userCommonRelationQueries: paramTemp,
      });
    }
    if (saveType === '新增') {
      addYearAndOtherAchieve.run({
        yearOrOther: '其他标志性成果',
        ...formRefData,
        userCommonRelationQueries: paramTemp,
      });
    }
    if (saveType === '更新') {
      updateYearAndOtherAchieve
        .run({
          yearOrOther: '其他标志性成果',
          ...formRefData,
          userCommonRelationQueries: paramTemp,
        })
        .then(() => {
          if (localStorage.getItem('isEdit') === '审核') {
            updateStatusIpi
              .run({
                tableName: 'YEAR_AND_OTHER_ACHIEVE',
                ids: [pageType],
                status: 2, //审核通过
                tab: '子方向视角',
              })
              .then(() => {
                history.goBack();
                message.success('操作成功');
              });
          }
        });
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  // 回填人员列表，以后写在暂存详情的接口中
  useEffect(() => {
    const pageTypeTemp = history.location.pathname.replace(
      '/LabAchievements/ScientificResearch/OtherAchievements/EditOtherAchievements/',
      '',
    );
    setPageType(pageTypeTemp);
    if (pageTypeTemp !== 'new') {
      findYearAndOtherAchieveDetailById.run({ id: pageTypeTemp }).then((e) => {
        setDescriptionData(e);
        const { year, ...eformdata } = e;
        formRef.current?.setFieldsValue({
          year: year ? moment(year, 'YYYY') : null,
          ...eformdata,
        });
      });
    }
  }, []);

  return (
    <PageContainer
      header={{
        title:
          findYearAndOtherAchieveDetailById?.data?.message &&
          findYearAndOtherAchieveDetailById?.data?.isPass != 4 ? (
            <div style={{ fontSize: 18, textAlign: 'center', color: 'red' }}>
              拒绝原因：{findYearAndOtherAchieveDetailById?.data?.message}
            </div>
          ) : null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>科学研究</Breadcrumb.Item>
            <Breadcrumb.Item>其他标志性成果</Breadcrumb.Item>
            <Breadcrumb.Item>
              {TitleAdapter(
                pageType,
                localStorage.getItem('isEdit'),
                '其他标志性成果',
              )}
            </Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      extra={
        <div>
          {localStorage.getItem('isEdit') === '审核' ? (
            <Space>
              <ModalForm
                title="拒绝"
                trigger={<Button key="2">返回成员修改</Button>}
                autoFocusFirstInput
                modalProps={{
                  onCancel: () => console.log('run'),
                  destroyOnClose: true,
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  console.log(values);
                  updateStatusIpi
                    .run({
                      tableName: 'YEAR_AND_OTHER_ACHIEVE',
                      ids: [pageType],
                      status: 3, //拒绝
                      message: values.message,
                      tab: '子方向视角',
                    })
                    .then(() => {
                      history.goBack();
                      message.success('操作成功');
                    });
                  return true;
                }}
                grid={true}
                initialValues={{
                  message: findYearAndOtherAchieveDetailById?.data?.message,
                }}
              >
                <ProForm.Group>
                  <ProFormText
                    name="message"
                    label="拒绝原因"
                    placeholder="请输入拒绝原因"
                    colProps={{ span: 24 }}
                    rules={[{ required: true, message: '请输入拒绝原因' }]}
                  />
                </ProForm.Group>
              </ModalForm>

              <Button
                key="1"
                type="primary"
                onClick={() => {
                  let formRefData: any = formRef.current?.getFieldsValue();
                  if (!formRefData?.annexPath) {
                    message.warning('请上传材料！');
                  } else {
                    if (pageType === 'new') {
                      setSaveType('新增');
                    } else {
                      setSaveType('更新');
                    }
                    getUserList
                      .run({
                        userList: formRefData.authors.replace(/，/g, ','),
                      })
                      .then((e) => {
                        showModal(e);
                      });
                  }
                }}
              >
                提交管理员审核
              </Button>
            </Space>
          ) : null}
        </div>
      }
      content={
        <>
          {localStorage.getItem('isEdit') === '查看' ? (
            <ProCard>
              <Descriptions bordered>
                {/* labelStyle={{ textAlign: 'center' }} */}
                {localStorage.getItem('identity') === '管理员' ? (
                  <>
                    <Descriptions.Item label="序号" labelStyle={{ width: 150 }}>
                      {descriptiondata?.seq}
                    </Descriptions.Item>
                    <Descriptions.Item label="年度" labelStyle={{ width: 140 }}>
                      {descriptiondata?.year}
                    </Descriptions.Item>
                  </>
                ) : null}
                <Descriptions.Item
                  label="成果名称"
                  span={3}
                  labelStyle={{ width: 140 }}
                >
                  {descriptiondata?.achieveName}
                </Descriptions.Item>
                <Descriptions.Item label="全部作者" span={3}>
                  {descriptiondata?.authors}
                </Descriptions.Item>
                <Descriptions.Item label="成果类别" span={3}>
                  {descriptiondata?.achieveType}
                </Descriptions.Item>
                <Descriptions.Item label="成果完成时间">
                  {descriptiondata?.achieveTime
                    ? moment(descriptiondata?.achieveTime).format('YYYY-MM-DD')
                    : null}
                </Descriptions.Item>
                <Descriptions.Item label="佐证材料">
                  {/* {descriptiondata?.annexPath} */}
                  <a
                    onClick={() => {
                      if (descriptiondata?.annexPath) {
                        window.open(descriptiondata?.annexPath);
                      } else {
                        message.info('未上传佐证材料');
                      }
                    }}
                  >
                    点击查看
                  </a>
                </Descriptions.Item>
                <Descriptions.Item label="标签" span={3}>
                  {getLabelAdapter(getAllLabel?.data, descriptiondata?.labels)}
                </Descriptions.Item>
              </Descriptions>
            </ProCard>
          ) : (
            <ProForm
              grid={true}
              layout="vertical"
              formRef={formRef}
              onFinish={async (values) => {
                if (!values?.annexPath) {
                  message.warning('没有上传材料，确认人员后即可提交！');
                }
                if (pageType === 'new') {
                  setSaveType('新增');
                } else {
                  setSaveType('更新');
                }
                getUserList
                  .run({ userList: values.authors.replace(/，/g, ',') })
                  .then((e) => {
                    showModal(e);
                  });
              }}
              autoFocusFirstInput
              submitter={{
                render: (_, dom) => (
                  <FooterToolbar>
                    {localStorage.getItem('isEdit') === '审核' ? null : (
                      <>
                        {pageType === 'new' ||
                        findYearAndOtherAchieveDetailById?.data?.isPass + '' ===
                          '-1' ? (
                          <Button
                            // type="primary"
                            key={'staging'}
                            onClick={() => {
                              setSaveType('暂存');
                              let values = formRef.current?.getFieldsValue();
                              if (values.authors) {
                                getUserList
                                  .run({
                                    userList: values.authors.replace(
                                      /，/g,
                                      ',',
                                    ),
                                  })
                                  .then((e) => {
                                    showModal(e);
                                  })
                                  .catch((e) => message.error('作者填写有误'));
                              } else {
                                addOrUpdateYearAndOtherAchieveTemp.run({
                                  ...formRef.current?.getFieldsValue(),
                                  yearOrOther: '其他标志性成果',
                                });
                              }
                            }}
                          >
                            暂存
                          </Button>
                        ) : null}
                        <Button
                          type="primary"
                          onClick={() => {
                            formRef.current?.submit();
                          }}
                        >
                          提交
                        </Button>
                      </>
                    )}
                  </FooterToolbar>
                ),
              }}
            >
              <ProFormDigit name={'id'} label={'编号'} hidden />
              <ProForm.Group title={'基本信息'}>
                <ProFormText
                  disabled
                  name="seq"
                  label="序号"
                  colProps={{ span: 4 }}
                  hidden={true}
                />
                <ProFormText
                  name={'achieveName'}
                  label={'其他重要成果及业绩、贡献名称'}
                  colProps={{
                    span: 4,
                  }}
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormText
                  name={'authors'}
                  label={'所有完成人员'}
                  colProps={{
                    span: 4,
                  }}
                  rules={[{ required: true, message: '请输入' }]}
                  placeholder="添加人员信息，以英文逗号分隔"
                />
                <ProFormSelect
                  options={[
                    {
                      value: '独立完成',
                      label: '独立完成',
                    },
                    {
                      value: '第一完成人(非独立完成)',
                      label: '第一完成人(非独立完成)',
                    },
                    {
                      value: '非第一完成人(非独立完成)',
                      label: '非第一完成人(非独立完成)',
                    },
                  ]}
                  name="completeState"
                  label="完成情况"
                  colProps={{ span: 4 }}
                  hidden={localStorage.getItem('identity') !== '管理员'}
                  rules={[{ required: true, message: '请选择' }]}
                />
              </ProForm.Group>
              <ProForm.Group title="详细内容">
                <ProFormDatePicker.Year
                  name={'year'}
                  label={'年度'}
                  colProps={{ span: 3 }}
                  hidden={localStorage.getItem('identity') !== '管理员'}
                />
                <ProFormText
                  name={'achieveType'}
                  label={'成果类别（例:2021年度中国电工技术学会科学技术奖）'}
                  colProps={{
                    span: 6,
                  }}
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormDatePicker
                  name={'achieveTime'}
                  label={'完成时间'}
                  colProps={{ span: 3 }}
                  rules={[{ required: true, message: '请输入' }]}
                />
              </ProForm.Group>
              <ProForm.Group title="佐证材料">
                <ProFormSelect
                  colProps={{ span: 3 }}
                  options={getAllLabel?.data}
                  mode="tags"
                  name="labels"
                  label="其他标志性成果标签"
                  hidden={localStorage.getItem('identity') !== '管理员'}
                  addonAfter={
                    <ModalForm<{
                      year: string;
                      labelName: string;
                    }>
                      title="新增标签"
                      trigger={<a>新增标签</a>}
                      autoFocusFirstInput
                      modalProps={{
                        onCancel: () => console.log('run'),
                      }}
                      submitTimeout={2000}
                      onFinish={async (values) => {
                        addLabelDetail.run(values);
                        return true;
                      }}
                    >
                      <ProForm.Group>
                        <ProFormDatePicker.Year
                          width="md"
                          name="year"
                          label="标签年份"
                          required
                        />
                        <ProFormText
                          width="md"
                          name="labelName"
                          label="标签名称"
                          required
                        />
                      </ProForm.Group>
                    </ModalForm>
                  }
                />
              </ProForm.Group>
              <ProFormText
                name={'annexPath'}
                label={'材料地址'}
                placeholder="待审核"
                hidden
              />
              <ProFormSelect
                name={'isPass'}
                label={'审核情况'}
                colProps={{ span: 6 }}
                placeholder="待审核"
                options={[
                  {
                    value: '0',
                    label: '缺失附件',
                  },
                  {
                    value: '1',
                    label: '审核中',
                  },
                  {
                    value: '2',
                    label: '审核通过',
                  },
                  {
                    value: '3',
                    label: '审核失败',
                  },
                ]}
                disabled
                hidden
              />
              <ProFormGroup>
                <ModalForm
                  title="上传材料"
                  trigger={
                    <Button icon={<UploadOutlined />} type="link">
                      上传材料（上传成果相关图片资料）
                    </Button>
                  }
                  autoFocusFirstInput
                  submitTimeout={2000}
                  onFinish={async (values) => true}
                >
                  <ProCard title={TbaleExplainMap['OTHER_REQRESENTATIVE']}>
                    {/* 有小问题，需要修改成pro的dragger */}
                    <Dragger {...props} maxCount={1}>
                      <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                      <p className="ant-upload-text">
                        单击或拖动文件到此区域进行上传
                      </p>
                      <p className="ant-upload-hint">请上传一个文件</p>
                    </Dragger>
                  </ProCard>
                </ModalForm>
                <Button
                  type="link"
                  onClick={() => {
                    descriptiondata?.annexPath
                      ? window.open(descriptiondata?.annexPath)
                      : message.info('请上传材料');
                  }}
                  icon={<FileSearchOutlined />}
                >
                  查看材料
                </Button>
              </ProFormGroup>
            </ProForm>
          )}
        </>
      }
    >
      <Modal
        title="请确认人员！"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        forceRender
      >
        <Table
          size="small"
          pagination={{ hideOnSinglePage: true, pageSize: 10 }}
          rowKey={'webId'}
          rowSelection={{
            onChange: (
              selectedRowKeys: React.Key[],
              selectedRows: DataType[],
            ) => {
              setSelectKeys(selectedRowKeys);
            },
            selectedRowKeys: selectKeys,
          }}
          columns={[
            {
              title: '工号',
              dataIndex: 'username',
              key: 'username',
            },
            {
              title: '姓名',
              dataIndex: 'realName',
              key: 'realName',
            },
            {
              title: '人员类型',
              dataIndex: 'userType',
              key: 'userType',
            },
          ]}
          dataSource={modalDataSource}
        />
      </Modal>
    </PageContainer>
  );
};
